﻿/**
* Notes.js controlador para la vistas del contenido general del aplicativo.
* Aqui se declaran los eventos generales y los comunes
* en el aplicativo.
*/
Ext.define("entgpv11.controller.Notes", {

    extend: "Ext.app.Controller",
    config:
    {
        viewCache: { get: function (name) { return (0); } },
        countTap: 0,
        refs:
        {
            mainContainer: "maincontainer",
            details: "details",
            notesListContainer: "notescontainer",
            noteEditor: "noteeditor",
            menuUser01: "menuuser01",
            usgsMap: "usgsmap",
            carousel: "imagelist",
            videoList: "videolist",
            menuUser02: "menuuser02",
            docList: "doclist",
            updateinfo: "updateinfo",
            backButton: '#buttonBackVideo',
            editButton: '#my-video-player',
            frameButton: '#video-frame',
            trafficButton: '#myTrafficButton',
            trackingButton: '#myTrackingButton',
            menuUser03: "menuuser03"
        },
        control:
        {
            carousel:
            {
                cameraButtonTapCommand: "onCameraButtonTapCommand"
            },
            usgsMap:
			{

			    trackingButtonTapCommand: "onTrackingButtonTapCommand",
			    trafficButtonTapCommand: "onTrafficButtonTapCommand"
			},
            notesListContainer:
            {

                backButtonTapCommand: "onBackButtonTapCommand",
                editNoteCommand: "onEditNoteCommand",
                exitButtonTapCommand: "onExitButtonTapCommand"
            },
            details:
            {
                show: "onShowDetails",
                backToHomeCommand: "onBackToHomeCommand",
                closeToolbarCommand: "onCloseToolbar",
                exitButtonTapCommand: "onExitButtonTapCommand",
                trackingButtonTapCommand: "onTrackingButtonTapCommand",
                trafficButtonTapCommand: "onTrafficButtonTapCommand"
            },
            videoList:
            {
                listItemTapCommand: "onListItemTapCommand",
                videoButtonCommand: "videoButtonCommand"
            },
            menuUser03:
            {
                btnSearchCommand: "onBtnSearchCommand"
            }
        }
    },
    // Transitions
    slideLeftTransition: { type: 'slide', direction: 'left' },
    slideRightTransition: { type: 'slide', direction: 'right' },

    // Helper functions

    getRandomInt: function (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    },
    /**
    * Realiza la busqueda de un determinado proyecto para mostrar el detalle del mismo
    * @record
    * @rol
    */
    activateNoteEditor: function (record, rol) {
        try {

            if (this.getCountTap() == 0) {

                var idNumber = Ext.Number.toFixed(record.get("Id"));
                var viewDetails = {
                    xtype: "details"
                };

                if (typeof record.resourseVideos != 'Object') {
                    record.resourseVideos = { videos: [] };

                }
                if (typeof record.resourseImages != 'Object') {
                    record.resourseImages = { imagenes: [] };

                }
                if (typeof record.resourseDocu != 'Object') {
                    record.resourseDocu = { documentos: {} };

                }
                if (Ext.Viewport.query('#tabDetails').length != 0) {

                    Ext.Viewport.remove(this.getDetails(), true);

                }
                Ext.Viewport.setMasked({
                    xtype: 'loadmask',
                    message: 'Cargando proyecto ' + record.get("Nombre").substring(0, 15) + ' ...'
                });
            }

            var rObject = {};
            Ext.Ajax.request({
                url: APP_GLOBAL.getServiceUrl() + "GetHtmlResources",
                disableCaching: false,
                scriptTag: true,
                method: 'POST',
                params: { id: idNumber },
                failure: function (response, opts) {
                    Ext.Viewport.unmask();
                    Ext.Msg.alert('Error', 'Los datos no pueden ser presentados de proyecto ' + record.get("Nombre").substring(0, 15) + ' ...', Ext.emptyFn);
                    //console.log('server-side failure with status code ' + response.status);
                },
                success: function (response, opts) {
                    rObject = Ext.decode(response.responseText);
                    if (rObject.imagenes.length != 0)
                        record.resourseImages.imagenes = rObject.imagenes;
                    //,if (rObject.videos.length != 0)
                    //,    record.resourseVideos.videos = rObject.videos;

                    record.resourseDocu.documentos = rObject.documentos;
                    this.setViewCache(record);
                    Ext.Viewport.unmask();
                    Ext.Viewport.animateActiveItem(viewDetails, this.slideLeftTransition);
                },
                scope: this
            });



        } catch (ex) {
            if (Ext.Viewport.getMasked())
                Ext.Viewport.unmask();
            Ext.Msg.alert('Error', 'Los datos no pueden ser presentados de proyecto ' + record.get("Nombre").substring(0, 15) + ' ...', Ext.emptyFn);
            APP_GLOBAL.SetLog(' activateNoteEditor::' + ex);
        }
    },
    /**
    * Muestra la informacion correspondiente a un proyecto.
    * 
    * 
    */
    showDetails: function () {
        try {

            tabs = Ext.getCmp('tabDetails');

            var record = this.getViewCache();

            if (record != null) {
                if (this.getCountTap() != 2) {
                    var idNumber = 0;
                    var nPointmap = 0;
                    var noteEditor = this.getNoteEditor();
                    this.getUsgsMap().addMarker(record);


                    this.getUsgsMap().getCountMarkersGlobal();

                    //if (typeof record.get !== 'function')
                    idNumber = Ext.Number.toFixed(record.get("Id"));
                    //noteEditor.setData(record.data);
                    noteEditor.setRecord(record); // load() is deprecated.

                    this.getDetails().setDataId(idNumber);
                    this.getUpdateinfo().setDataId(idNumber);
                    //,this.getVideoList().addContainerItems(record.resourseVideos.videos);
                    this.getDocList().addContainerItems(record.resourseDocu.documentos);
                    this.getCarousel().addContainerItems(record.resourseImages.imagenes);
                }



            }
            if (this.getCountTap() == 2)
                tabs.setActiveItem(3);
            else
                tabs.setActiveItem(0);

            this.setCountTap(1);

        } catch (ex) {
            APP_GLOBAL.SetLog(' showDetails::' + ex);
        }
    },
    /**
    * Muestra el video tipo youtube en un frame.
    * 
    * 
    */
    activateListVideo: function () {
        try {
            var player = this.getEditButton(); //player = Ext.getCmp('my-video-player');
            var frame = this.getFrameButton(); // frame = Ext.getCmp('video-frame');
            var listVideo = Ext.getCmp('video-list');
            this.getDetails().setBackType('back');

            listVideo.setHidden(false);
            player.setHidden(true);
            frame.setHidden(true);
            player.pause();

        } catch (ex) {
            APP_GLOBAL.SetLog(' activateListVideo::' + ex);
        }

    },
    /**
    * @private
    */
    activateNotesList: function () {
        this.setCountTap(0);
        Ext.Viewport.animateActiveItem(this.getNotesListContainer(), this.slideRightTransition);
    },
    /**
    * @private
    */
    reachableCallback: function (reachability) {
    },

    // Commands.

    /**
    * @private
    */
    onBtnMapTapCommand: function () {
        try {
            var noteEditor = this.getNoteEditor();
            var recordSelect = noteEditor.getRecord();

            var view = Ext.create('entgpv11.view.UsgsMap', {
                dataLatLng: recordSelect.data
            });
            // addMap
            Ext.Viewport.animateActiveItem(view, this.slideLeftTransition);
        } catch (ex) {
            APP_GLOBAL.SetLog('onBtnMapTapCommand::' + ex);
        }

    },

    /**
    * @private
    */
    onBackButtonDetailCommand: function () {
        try {
            var formback = this.getNoteEditor();
            Ext.Viewport.animateActiveItem(formback, this.slideLeftTransition);

        } catch (ex) {
            APP_GLOBAL.SetLog('onBackButtonDetailCommand::' + ex);
        }

    },

    /**
    * CAROUSEL:
    * {
    *    cameraButtonTapCommand: "onCameraButtonTapCommand"
    * }   
    *        
    */

    /**
    * Al tomar la foto se presenta el carrusel de imagenes
    *
    */
    onCameraButtonTapCommand: function () {
        try {

            var formback = {
                xtype: 'imagecamera'
            };
            this.setCountTap(2); //Count determina accion page
            Ext.Viewport.animateActiveItem(formback, this.slideLeftTransition);

        } catch (ex) {
            APP_GLOBAL.SetLog('onCameraButtonTapCommand::' + ex);
        }

    },
    /**
    * USGSMAP:
    * {
    *   trackingButtonTapCommand: "onTrackingButtonTapCommand",
    *	trafficButtonTapCommand: "onTrafficButtonTapCommand"
    * }   
    *        
    */

    /**
    * Muestra el punto de referencia del proyecto escogido
    *
    * 
    */
    onTrackingButtonTapCommand: function () {
        var record = this.getViewCache();

        if (record != null) {
            this.getUsgsMap().addMarker(record);
        }
    },
    /**
    * Muestra todos los puntos de referencia de los proyectos escogidos
    *
    * 
    */
    onTrafficButtonTapCommand: function () {
        var tabs = Ext.getCmp('tabDetails');
        tabs.setActiveItem(2);
        this.getUsgsMap().showGlobalOverlays();
    },
    /**
    *NOTESLISTCONTAINER:
    *{
    *
    *   backButtonTapCommand: "onBackButtonTapCommand",
    *   editNoteCommand: "onEditNoteCommand",
    *   exitButtonTapCommand: "onExitButtonTapCommand"
    *}
    *        
    */

    /**
    * Muestra la interfaz anterior segun el rol
    *
    * 
    */
    onBackButtonTapCommand: function (me) {
        try {
            var formback = null;
            if (me.getRol() == "RAF") {
                formback = this.getMenuUser02();
                Ext.Viewport.animateActiveItem(formback, this.slideLeftTransition);
            }
            else {
                formback = this.getMenuUser01();
                Ext.Viewport.animateActiveItem(formback, this.slideLeftTransition);

            }
        } catch (ex) {
            APP_GLOBAL.SetLog('onBackButtonTapCommand::' + ex);
        }
    },
    /**
    * Activa interfaz detalle
    * @list
    * @record
    * @rol
    */
    onEditNoteCommand: function (list, record, rol) {
        try {
            this.activateNoteEditor(record, rol);
        } catch (ex) {
            APP_GLOBAL.SetLog('onEditNoteCommand::' + ex);
        }
    },
    /**
    * Salir del aplicativo y muestra la primera interfaz
    * 
    * 
    */
    onExitButtonTapCommand: function () {
        try {
            this.setCountTap(0);
            Ext.Viewport.animateActiveItem(this.getMainContainer(), this.slideLeftTransition);
        } catch (ex) {
            APP_GLOBAL.SetLog('onExitButtonTapCommand::' + ex);
        }

    },
    /**
    *  DETAILS:
    *  {
    *           show: "onShowDetails",
    *           backToHomeCommand: "onBackToHomeCommand",
    *           closeToolbarCommand: "onCloseToolbar",
    *           exitButtonTapCommand: "onExitButtonTapCommand",
    *           trackingButtonTapCommand: "onTrackingButtonTapCommand",
    *           trafficButtonTapCommand: "onTrafficButtonTapCommand"
    *  }
    *        
    */
    onShowDetails: function () {
        this.showDetails();
    },
    /**
    * Iterfaz listado de proyectos cuando esta activa interfaz detalle
    * @me
    */
    onBackToHomeCommand: function (me) {
        try {
            //if (me.getBackType() == 'back')
            this.activateNotesList();
            //else
            //this.activateListVideo();

        } catch (ex) {
            APP_GLOBAL.SetLog('onBtnMapTapCommand::' + ex);
        }
    },
    /**
    * Evento al realizar click tool de detalle
    * @tabBar
    * @newTab
    * @oldTab
    */
    onCloseToolbar: function (tabBar, newTab, oldTab) {
        try {
            var index = tabBar.indexOf(newTab);
            //Tab Imagenes
            if (index == 4) {
                var myImgs = this.getCarousel().down('carousel');
                if (myImgs) {
                    index = myImgs.getActiveIndex();
                    if (index == -1)
                        myImgs.setActiveItem(0);
                }
            }
        } catch (ex) {
            APP_GLOBAL.SetLog('onCloseToolbar::' + ex);
        }

    },
    /**
    *  VIDEOLIST:
    *       {
    *           listItemTapCommand: "onListItemTapCommand",
    *           videoButtonCommand: "videoButtonCommand"
    *       }
    *        
    */
    /**
    * Iterfaz  detalle de video
    * @ref
    * @list
    * @record
    */
    onListItemTapCommand: function (ref, list, record) {
        try {
            var player = this.getEditButton(); //player = Ext.getCmp('my-video-player');
            var frame = this.getFrameButton(); // frame = Ext.getCmp('video-frame');
            var btn = this.getBackButton();
            this.getDetails().setBackType('back-video');

            btn.setHidden(false);
            if (record.get("youtube") == "true") {
                w = Ext.os.deviceType == 'Phone' ? 100 : 500;
                h = Ext.os.deviceType == 'Phone' ? 100 : 500;
                frame.setHtml('<iframe class="youtube-player" width="' + w + '" height="' + h + '" type="text/html" frameborder="0" src="' + record.get("src") + '"></iframe>');
                frame.setHidden(false);
                player.setHidden(true);
            }
            else {
                frame.setHidden(true);
                player.setUrl(record.get("src"));
                player.updatePosterUrl("./resources/images/video/screenshot02.png");
                player.setHidden(false);
                player.play();
            }
            list.setHidden(true);
        } catch (ex) {
            APP_GLOBAL.SetLog('onListItemTapCommand::' + ex);
        }

    },
    /**
    * Iterfaz listado de videos cuando esta activa interfaz detalle de video
    * @me
    */
    videoButtonCommand: function (me) {
        try {
            var btn = this.getBackButton();
            btn.setHidden(true);
            this.activateListVideo();

        } catch (ex) {
            APP_GLOBAL.SetLog('onBtnMapTapCommand::' + ex);
        }
    },
    /**
    *  MENUUSER03:
    *       {
    *          
    *       }
    *        
    */
    onBtnSearchCommand: function (me) {
        try {
            var form = this.getMenuUser03().getValues();
            var model = Ext.ModelMgr.create(form, 'entgpv11.model.Filter');
            model.addValidations(
			{
			    field: 'Key',
			    type: 'presence',
			    message: 'Año es requerido'
			});
            if (form["sMesId"] == "Ninguno")
                form["sMesId"] = "";
            var errors = model.validate(), message = "";
            if (errors.isValid()) {
                Ext.Viewport.setMasked({
                    xtype: 'loadmask',
                    message: 'Cargando datos'
                });
                Ext.Ajax.request({
                    url: APP_GLOBAL.getServiceUrl() + "ReadDroboxExcel",
                    disableCaching: false,
                    scriptTag: true,
                    method: 'POST',
                    params: { anyo: form["sAnyoId"], mes: form["sMesId"] },
                    failure: function (response, opts) {
                        Ext.Viewport.unmask();
                        Ext.Msg.alert('Error', 'Los datos no pueden ser presentados ..', Ext.emptyFn);
                        //console.log('server-side failure with status code ' + response.status);

                    },
                    success: function (response, opts) {
                        var rObject = Ext.decode(response.responseText);
                        var store_data = Ext.create("entgpv11.store.ExcelDropBox");
                        var grid = Ext.getCmp('gridExcel');
                        store_data.setData(rObject.listExcel);
                        grid.setStore(store_data);
                        //grid.doComponentLayout(); // this is the trick!
                        grid.refresh();
                        //if (grid.rendered) {
                        //    grid.scroller.scrollTo({ x: 0, y: 0 });
                        //}
                        grid = Ext.getCmp('gridExcelHead');
                        if (rObject.listExcel.length == 0) {
                            grid.setStore({ fields: ["Mes", "Ingreso", "Egreso", "Saldo"], data: [{ Mes: "", Ingreso: "", Egreso: "", Saldo: ""}] });
                        } else {
                            grid.setStore({ fields: ["Mes", "Ingreso", "Egreso", "Saldo"], data: [{ Mes: "Mes", Ingreso: "Ingreso", Egreso: "Egreso", Saldo: "Saldo"}] });
                        }
                        grid.refresh();
                        Ext.Viewport.unmask();
                    },
                    scope: this
                });
            }

        } catch (ex) {
            APP_GLOBAL.SetLog('onBtnMapTapCommand::' + ex);
        }
    },

    // Base Class functions.
    launch: function () {
        try {
            this.callParent(arguments);
            //var notesStore = Ext.getStore("Notes");
            //notesStore.load();

        } catch (ex) {
            APP_GLOBAL.SetLog(ex);
        }
    },
    init: function () {
        this.callParent(arguments);
    }
});